package Server.Login;

import Protobuf.ChatProto;
import Protobuf.DbProto;
import Server.Cache.MsgSession;
import Server.Cache.PlayerCache;
import Server.Common.Player;
import Server.DbClientHandler;

public class Login extends TransferMsg {


    /**发送登录请求到数据库服务器，验证登录数据*/
    @Override
    public void sendDbPacket(MsgSession session) {
        ChatProto.Msg msg = session.getMsg();
        ChatProto.Login login = msg.getLogin();
        String username = login.getUsername();
        String psd = login.getPsd();
        String channelId = session.getChannelId();
        DbProto.Msg retMsg = DbProto.Msg.newBuilder().setMsgType(DbProto.Msg.MsgType.log).setChannelId(channelId)
                .setLogin(DbProto.Login.newBuilder().setUsername(username).setPsd(psd).setPsd(psd).build())
                .build();
        DbClientHandler.getDbServerCtx().writeAndFlush(retMsg);
    }

    public void loginStatus(DbProto.Msg msg) {//获取登录结果
        long id = msg.getPlayer().getId();
        String username = msg.getPlayer().getUsername();
        if(PlayerCache.getInstance().isContainsPlayer(id)){
            preempt(id);
        }
        ChatProto.RespLogin.LoginResult type = null;
        boolean loginResult = false;
        if(id == 0){
            type = ChatProto.RespLogin.LoginResult.usernameNotExist;
        }else if( id == 1){
            type = ChatProto.RespLogin.LoginResult.passwordError;
        }
        if (id > 1){
            type = ChatProto.RespLogin.LoginResult.loginSuccess;
            Player player = Player.create(msg,id,username);
            player.load();
            loginResult = true;

        }
        if(type != null) {
            loginResponse(type, loginResult, msg.getChannelId(), id, msg.getPlayer().getName());
        }
    }

    /**如果用户在其他地方登陆，该处被抢占*/
    private void preempt(long id){
        ChatProto.Msg loginAgain = ChatProto.Msg.newBuilder().setMsgType(ChatProto.Msg.MsgType.suc)
                .setRespLogin(ChatProto.RespLogin.newBuilder().setLoginResult(ChatProto.RespLogin.LoginResult.otherPlayerLogin).build())
                .build();
        //该用户在线，告诉在线用户在其他地方上线了，该客户端将断开连接
        PlayerCache.getInstance().getPlayer(id).sendMsg(loginAgain);
        PlayerCache.getInstance().getPlayer(id).getChannel().close();
    }
}
